<template>
	<a-form ref="searchFormRef" name="advanced_search" :model="formState" :label-col="{ span: 6 }" class="mb-4 ant-advanced-search-form">
		<a-row :gutter="24">
			<!-- 使用具名插槽来接收字段内容，父组件通过插槽提供输入控件 -->
			<template v-for="(item, index) in formFields" :key="index">
				<a-col :span="item.span || 6" v-if="!item.advanced || advanced">
					<a-form-item :name="item.name" :rules="item.rules">
						<template #label>
							<a-tooltip :title="item.label" placement="top">
								<span style="display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap">
									{{ item.label }}
								</span>
							</a-tooltip>
						</template>
						<slot :name="item.slot || item.name" :item="item" :formState="formState">
							<!-- 插槽内容由父组件提供，这里不定义默认内容 -->
						</slot>
					</a-form-item>
				</a-col>
			</template>

			<!-- 操作按钮区域 -->
			<a-col :span="buttonSpan" class="ctrl-buttons" style="display: flex; justify-content: flex-end; align-items: center; padding: 12px; padding-top: 0">
				<a-button size="small" type="primary" @click="handleSearch">查询</a-button>
				<a-divider type="vertical" />
				<a-button size="small" @click="handleReset">重置</a-button>
				<a-divider type="vertical" />
				<a-button size="small" type="link" @click="toggleAdvanced">
					{{ advanced ? '收起' : '展开' }}
					<i :class="advanced ? 'fa fa-chevron-up' : 'fa fa-chevron-down'" style="margin-left: 4px" />
				</a-button>
			</a-col>
		</a-row>
	</a-form>
</template>

<script setup name="SearchForm">
	import { ref, computed } from 'vue'
	import { Form, Row, Col, Button } from 'ant-design-vue'

	const props = defineProps({
		formState: {
			type: Object,
			required: true
		},
		formFields: {
			type: Array,
			required: true,
			default: () => []
		}
	})

	const emit = defineEmits(['search', 'reset'])

	const searchFormRef = ref()
	const advanced = ref(false)

	// 计算操作按钮的span值，确保始终在最后一格
	const buttonSpan = computed(() => {
		// 获取当前显示的字段
		const visibleFields = props.formFields.filter((item) => !item.advanced || advanced.value)
		// 计算当前行已占用的span
		const totalSpan = visibleFields.reduce((sum, item) => sum + (item.span || 6), 0)
		// 计算当前行剩余的span
		const remainingSpan = 24 - (totalSpan % 24)
		// 如果剩余空间足够放按钮(至少6个span)，则使用剩余空间，否则使用6个span
		return remainingSpan >= 6 ? remainingSpan : 6
	})

	const toggleAdvanced = () => {
		advanced.value = !advanced.value
	}

	const handleSearch = () => {
		emit('search')
	}

	const handleReset = () => {
		searchFormRef.value?.resetFields()
		emit('reset')
	}

	// 暴露方法给父组件
	const resetFields = () => {
		searchFormRef.value?.resetFields()
	}

	defineExpose({
		resetFields
	})
</script>

<style scoped lang="less"></style>
